package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ArrayUtil;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.model.entity.UserEntity;
import com.qire.manhua.dal.IUserDataDAL;
import com.qire.manhua.model.viewModel.impl.AccountsAssociatedViewModel;
import com.qire.manhua.model.vo.AccountRelatedInfoVO;
import com.qire.manhua.model.vo.AccountRelatedInfoVO.AccountItemVO;
import com.qire.manhua.model.vo.LoginRespVO;
import com.qire.manhua.model.vo.UserDetailVO;

public class AccountsAssociatedService extends DataService {

    private final IUserDataDAL userDataDAL = WarehouseFactory.create(this, IUserDataDAL.class);

    private final AccountsAssociatedViewModel viewModel;

    public AccountsAssociatedService(AccountsAssociatedViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 加载相关关联账户列表
     */
    public void loadAccountRelatedInfo() {
        userDataDAL.fetchAccountRelatedInfoList();
    }
    @StrategyAnnotation(event = {Url.AccountRelatedInfoList})
    public void fetchAccountRelatedInfoListCallback(AccountRelatedInfoVO data, boolean isCache) {
        if(ObjectUtil.isNull(data) || ArrayUtil.isEmpty(data.users)) {
            return;
        }
        for(int index = 0; index < data.users.length; index++) {
            AccountItemVO itemVO = data.users[index];
            viewModel.addAccountsAssociatedItem(index + 1, itemVO.userid, itemVO.user_name, itemVO.last_login_time,
                    itemVO.user_hash, itemVO.user_img, itemVO.coin, itemVO.bean, itemVO.vip == 1);
        }
        viewModel.refreshAccountAdapter();
    }

    /**
     * 切换到关联账户登录
     * @param userId    用户ID
     * @param userHash  用户Hash值
     * @param activityName 调用页
     */
    public void toggleLoginAccount(int userId, String userHash, String activityName) {
        userDataDAL.toggleAccount(userId, userHash, activityName);
    }
    @StrategyAnnotation(event = {Url.AccountToggleLogin})
    public void toggleAccountCallback(LoginRespVO dataVO, boolean isCache) {
        UserEntity.self.login(dataVO.userid, dataVO.token);
        viewModel.loadAccountRelatedInfo();
        loadLoginUserData();
    }

    /**
     * 加载登录的用户信息
     */
    private void loadLoginUserData() {
        userDataDAL.refreshUserDetailData();
        new TeensModeService().queryTeensModeState();
    }
    @StrategyAnnotation(event = Url.myIndex)
    public void refreshUserDetailDataCallback(UserDetailVO dataVO, boolean isCache) {
        if(ObjectUtil.nonNull(dataVO) && !isCache) {
            dataVO.updateUserEntity();
        }
    }

}
